package com.zhizuobiao.test1;

import java.lang.reflect.Field;

/**
 * 利用反射获取注解
 */
public class AnnotationTest {

    public static void main(String[] args) throws ClassNotFoundException {
        test2();
    }

    public static void test2() throws ClassNotFoundException {
        Class clazz = Class.forName("com.zhizuobiao.test1.HelloService");

        // 判断类中是否使用MyService注解
        boolean isExist = clazz.isAnnotationPresent(MyService.class);

        if (isExist) {
            // 获取类上的MyService注解
            MyService myService = (MyService) clazz.getAnnotation(MyService.class);
            // 使用MyService获取值
            System.out.println(myService.value());
        }
        // 获取类中的成员变量数组
        Field[] fields = clazz.getDeclaredFields();
        for (Field f : fields) {
            boolean fieldExist = f.isAnnotationPresent(MyAutowired.class);
            if (fieldExist) {
                MyAutowired myAutowired = f.getAnnotation(MyAutowired.class);
                System.out.println("成员变量："+f.getName());
                System.out.println(myAutowired.address());
                System.out.println(myAutowired.name());
                System.out.println(myAutowired.age());
            }
        }
    }

    public static void test1() throws ClassNotFoundException {
        Class clazz = Class.forName("com.zhizuobiao.test1.HelloService");
        boolean isExist = clazz.isAnnotationPresent(MyService.class);
        if (isExist) {
            MyService myService = (MyService) clazz.getAnnotation(MyService.class);
            System.out.println(myService.value());
        }
    }
}
